<?php
/**
 * Address Class. Remember to add $noNeedRight.
 * @Author: phpzhi <phpzhi@qq.com>
 * @Date: 2019/11/11 10:50
 */

namespace app\api\controller\user;


use app\common\controller\Api;
use app\common\model\user\Address as AddressModel;
use think\exception\ValidateException;

class Address extends Api
{
    protected $noNeedRight = ['*'];

    /**
     * user address list.
     */
    public function index()
    {
        $data = AddressModel::getUserAddress($this->auth->id);
        $this->success(__('Request successful'), ['data' => $data]);
    }

    /**
     * Update user address.
     */
    public function edit()
    {
        $model = new AddressModel();
        $msg = $this->request->post('id') > 0 ? __('Update successful') : __('Create successful');
        if ($model->edit($this->auth->id, $this->request->post())) {
            $this->success($msg);
        }
        $this->error($msg);
    }

    /**
     * user address detail.
     * @param $id
     */
    public function view($id)
    {
        $data = AddressModel::detail($this->auth->id, $id);
        $this->success(__('Request successful'), $data);
    }

    /**
     * delete user address.
     * @param $id
     */
    public function delete($id)
    {
        if (!$id || !is_numeric($id)) $this->error('参数错误！');
        $model = new AddressModel();
        if ($model->del($this->auth->id, $id)) {
            $this->success(__('Delete successful'));
        } else {
            $this->error(__('Address does not exist'));
        }
        $this->error(__('Delete failed'));
    }

    /**
     * set user a default address.
     * @param $id
     */
    public function setdefault($id)
    {
        if (!$id || !is_numeric($id)) $this->error(__('Param is incorrect'));
        $model = new AddressModel;
        if ($model->setDefault($this->auth->id, $id)) {
            $this->success(__('Setting successful'), AddressModel::detail($this->auth->id, $id));
        }
        $this->error(__('Setting failed'));
    }
}